<template>
  <div class="popupSelect-container">
    <div
      class="el-select"
      @click.stop="openDialog"
      @mouseenter="inputHovering = true"
      @mouseleave="inputHovering = false"
    >
      <div
        class="el-select__tags"
        v-if="multiple"
        ref="tags"
        :style="{
          'max-width': inputWidth - 32 + 'px',
          width: '100%',
          cursor: 'pointer',
        }"
      >
        <span v-if="collapseTags && tagsList.length">
          <el-tag
            :closable="!selectDisabled"
            :size="collapseTagSize"
            type="info"
            @close="deleteTag($event, 0)"
            disable-transitions
          >
            <span class="el-select__tags-text">{{ tagsList[0] }}</span>
          </el-tag>
          <el-tag
            v-if="tagsList.length > 1"
            :closable="false"
            type="info"
            disable-transitions
          >
            <span class="el-select__tags-text"
              >+ {{ tagsList.length - 1 }}</span
            >
          </el-tag>
        </span>
        <transition-group @after-leave="resetInputHeight" v-if="!collapseTags">
          <el-tag
            v-for="(item, i) in tagsList"
            :key="item"
            :size="collapseTagSize"
            :closable="!selectDisabled"
            type="info"
            @close="deleteTag($event, i)"
            disable-transitions
          >
            <span class="el-select__tags-text">{{ item }}</span>
          </el-tag>
        </transition-group>
      </div>
      <el-input
        ref="reference"
        v-model="innerValue"
        type="text"
        :placeholder="tagsList && tagsList.length ? '' : currentPlaceholder"
        :disabled="selectDisabled"
        readonly
        :validate-event="false"
        :tabindex="multiple ? '-1' : null"
        :title="innerValue"
      >
        <template #suffix>
          <el-icon v-show="!showClose">
            <ArrowDown />
          </el-icon>
          <el-icon v-if="showClose" @click.stop="handleClearClick">
            <CircleClose />
          </el-icon>
        </template>
      </el-input>
    </div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="visible"
      class="ZHLX-dialog ZHLX-dialog_center transfer-dialog"
      lock-scroll
      append-to-body
      width="800px"
      :modal-append-to-body="false"
      @close="onClose"
      style="display: block"
    >
      <div class="transfer__body">
        <div class="transfer-pane">
          <div class="transfer-pane__tools">
            <el-input
              placeholder="请输入关键词查询"
              v-model="keyword"
              @keyup.enter="search"
              clearable
              class="search-input"
            >
              <!-- <el-button slot="append" icon="el-icon-search" @click="search"></el-button> -->
              <template #append>
                <el-icon @click="search">
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </div>
          <div class="transfer-pane__body">
            <el-tabs
              v-model="activeName"
              class="transfer-pane__body-tab"
              :class="{ 'hasSys-tab': hasSys }"
              v-if="selectType === 'all'"
            >
              <el-tab-pane label="全部数据" name="all">
                <el-tree-v2
                  :height="300"
                  :data="treeData"
                  :props="props"
                  check-on-click-node
                  @node-click="handleNodeClick"
                  class="ZHLX-common-el-tree"
                  node-key="id"
                  v-loading="loading"
                  lazy
                  :load="loadNode"
                  v-if="!isAsync"
                >
                  <template v-slot:default="{ node, data }">
                    <span class="custom-tree-node">
                      <i :class="data.icon"></i>
                      <span class="text">{{ node.label }}</span>
                    </span>
                  </template>
                </el-tree-v2>
                <div
                  class="single-list"
                  ref="infiniteBody"
                  v-if="isAsync"
                  v-loading="loading && pagination.currentPage == 1"
                >
                  <template v-if="treeData.length">
                    <div
                      v-for="(item, index) in treeData"
                      :key="index"
                      class="selected-item-user"
                      @click="handleNodeClick(item)"
                    >
                      <div class="selected-item-main">
                        <el-avatar
                          :size="36"
                          :src="item.headIcon"
                          class="selected-item-headIcon"
                        >
                        </el-avatar>
                        <div class="selected-item-text">
                          <p class="name">{{ item.fullName }}</p>
                          <p class="organize" :title="item.organizeDesc">
                            {{ item.organizeDesc }}
                          </p>
                        </div>
                      </div>
                    </div>
                  </template>
                  <el-empty
                    description="暂无数据"
                    :image-size="120"
                    v-else
                  ></el-empty>
                </div>
              </el-tab-pane>
              <el-tab-pane label="组织人员" name="departmentuser">
                <el-tree-v2
                  v-if="treeData"
                  :height="300"
                  :data="treeData"
                  :props="props"
                  check-on-click-node
                  @node-click="handleNodeClick"
                  class="ZHLX-common-el-tree"
                  node-key="id"
                  v-loading="loading"
                  lazy
                  :load="loadNode2"
                >
                  <template v-slot:default="{ node, data }">
                    <span class="custom-tree-node">
                      <i :class="data.icon"></i>
                      <span class="text" :title="data.organizeDesc || ''">{{
                        node.label
                      }}</span>
                    </span>
                  </template>
                </el-tree-v2>
                <el-empty
                  description="暂无数据"
                  :image-size="120"
                  v-else
                ></el-empty>
              </el-tab-pane>
              <el-tab-pane label="系统变量" name="system">
                <el-tree-v2
                  :height="300"
                  :data="treeData"
                  :props="props"
                  :expand-on-click-node="false"
                  check-on-click-node
                  @node-click="handleNodeClick2"
                  class="ZHLX-common-el-tree"
                  node-key="id"
                  v-loading="loading"
                >
                  <template v-slot:default="node">
                    <span class="custom-tree-node">
                      <i class="icon-lx icon-lx-tree-user2"></i>
                      <span class="text">{{ node.label }}</span>
                    </span>
                  </template>
                </el-tree-v2>
              </el-tab-pane>
            </el-tabs>
            <template v-else>
              <div class="custom-title">全部数据</div>
              <div class="single-list" ref="infiniteBody">
                <template v-if="ableList.length">
                  <div
                    v-for="(item, index) in ableList"
                    :key="index"
                    class="selected-item-user"
                    @click="handleNodeClick2(item)"
                  >
                    <div class="selected-item-main">
                      <el-avatar
                        :size="36"
                        :src="item.headIcon"
                        class="selected-item-headIcon"
                      >
                      </el-avatar>
                      <div class="selected-item-text">
                        <p class="name">{{ item.fullName }}</p>
                        <p class="organize" :title="item.organize">
                          {{ item.organize }}
                        </p>
                      </div>
                    </div>
                  </div>
                </template>
                <el-empty
                  description="暂无数据"
                  :image-size="120"
                  v-else
                ></el-empty>
              </div>
            </template>
         
          </div>
        </div>
        <div class="transfer-pane">
          <div class="transfer-pane__tools">
            <span>已选</span>
            <el-input
              placeholder="请输入关键词查询"
              v-model="keywordSearch"
              clearable
              class="search-input"
              style="width: 260px"
            ></el-input>
            <el-button @click="removeAll" type="text" class="removeAllBtn"
              >清空列表
            </el-button>
          </div>
          <div class="transfer-pane__body shadow right-pane">
            <template v-if="selectedData.length">
              <div
                v-for="(item, index) in selectedData"
                :key="index"
                class="selected-item-user"
              >
                <div class="selected-item-main">
                  <el-avatar
                    :size="36"
                    :src="item.headIcon"
                    class="selected-item-headIcon"
                  >
                  </el-avatar>
                  <div class="selected-item-text">
                    <p class="name">{{ item }}</p>
                    <p class="organize" :title="item.organizeDesc">
                      {{ item.organizeDesc }}
                    </p>
                  </div>
                  <i class="el-icon-delete" @click="removeData(index)"></i>
                </div>
              </div>
            </template>
            <el-empty
              description="暂无数据"
              :image-size="120"
              v-else
            ></el-empty>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setDefault(), (visible = false)">取消</el-button>
          <el-button type="primary" @click="confirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import data from "./data";
export default {
  name: "ZHLX-comSelect",
  inject: {
    elForm: {
      default: "",
    },
    elFormItem: {
      default: "",
    },
  },
  // components: { VueEasyTree },
  props: {
    allCompany: {
      type: Boolean,
      default: false,
    },
    department: {
      type: Boolean,
      default: false,
    },
    modelValue: {
      default: () => [],
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    collapseTags: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: false,
    },
    auth: {
      type: Boolean,
      default: false,
    },
    isOnlyOrg: {
      type: Boolean,
      default: false,
    },
    size: String,
    currOrgId: {
      default: "0",
    },
    parentId: {
      default: "",
    },
    title: {
      default: "选择组织",
    },
    tenantOrganize: {
      // 租户组织
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      treeData: [],
      allList: [],
      ableList: [],
      keyword: "",
      innerValue: "",
      visible: false,
      loading: false,
      props: {
        children: "children",
        label: "fullName",
        isLeaf: "isLeaf",
      },
      selectedData: [],
      selectedIds: [],
      tagsList: [],
      inputHovering: false,
      inputWidth: 0,
      initialInputHeight: 0,
      selectType: "all",
      activeName: "all",
      keywordSearch: "",
      hasSys: false,
      isAsync: false,
      pagination: {
        currentPage: 1,
      },
    };
  },
  computed: {
    // ...mapGetters(['userInfo']),
    showClose() {
      let hasValue =
        Array.isArray(this.modelValue) && this.modelValue.length > 0;
      let criteria =
        this.clearable &&
        !this.selectDisabled &&
        this.inputHovering &&
        hasValue;
      return criteria;
    },
    currentPlaceholder() {
      if (
        this.multiple &&
        Array.isArray(this.modelValue) &&
        this.modelValue.length
      ) {
        return "";
      } else {
        return this.placeholder;
      }
    },
    selectDisabled() {
      return this.disabled || (this.elForm || {}).disabled;
    },
    _elFormItemSize() {
      return (this.elFormItem || {}).elFormItemSize;
    },
    selectSize() {
      return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
    },
    collapseTagSize() {
      return ["small", "mini"].indexOf(this.selectSize) > -1 ? "mini" : "small";
    },
  },
  created() {
    this.getData();
  },
  mounted() {

    const reference = this.$refs.reference;
    if (reference && reference.$el) {
      const sizeMap = {
        medium: 36,
        small: 32,
        mini: 28,
      };
      const input = reference.$el.querySelector("input");
      this.initialInputHeight =
        input.getBoundingClientRect().height || sizeMap[this.selectSize];
    }
    if (this.multiple) {
      this.resetInputHeight();
    }
    this.$nextTick(() => {
      if (reference && reference.$el) {
        this.inputWidth = reference.$el.getBoundingClientRect().width;
      }
    });
    this.setDefault();
  },
  beforeDestroy() {
  },
  watch: {
    modelValue(val) {
      this.setDefault();
    },
    multiple() {
      this.$nextTick(() => {
        this.resetInputHeight();
        this.clear();
      });
    },
    selectDisabled() {
      this.$nextTick(() => {
        this.resetInputHeight();
      });
    },
    allList: {
      handler: function (val) {
        this.setDefault();
      },
      deep: true,
    },
  },
  methods: {
    handleNodeClick2(item) {},
    loadNode2() {},
    loadNode() {},
    async getData() {
      let treeData;
      // if (this.allCompany) {
      //   treeData = await useGeneratorState().getDepTreeAll(this.department)
      // } else {
      //   treeData = await useGeneratorState().getDepTree()
      // }
      treeData = data;

      const topItem = {
        fullName: "顶级节点",
        hasChildren: true,
        id: "-1",
        icon: "icon-lx icon-lx-tree-organization3",
        organize: "顶级节点",
        organizeIds: ["-1"],
        children: treeData,
      };
      this.allList = [...treeData[0].children, topItem];
      this.treeData = [topItem];
      // this.allList = [...this.$store.getters.departmentList, topItem]
      if (this.tenantOrganize) {
        // 查租户组织
        this.treeData = await this.getTenantChildOrganizeAuthTreeData();
      } else {
        if (this.auth) {
          if (this.isOnlyOrg && this.parentId === "-1") {
            this.treeData = [topItem];
            return;
          }
          // const method = this.isOnlyOrg ? getOrganizeSelectorByAuth : getDepartmentSelectorByAuth
          // method(this.currOrgId).then(res => {
          //   const list = res.data.list
          //   let newList = []
          //   if (this.userInfo.isAdministrator) {
          //     topItem.children = treeData
          //     newList = [
          //       {
          //         ...topItem,
          //         children: list
          //       }
          //     ]
          //   } else {
          //     newList = list
          //   }
          //   this.treeData = newList
          // })
        } else {
          const newData = JSON.parse(JSON.stringify(treeData));
          // 单位、公司过滤数据，组织不过滤
          this.treeData = this.isOnlyOrg
            ? this.filterTreeArray(newData, "company")
            : newData;
        }
      }
    },
    filterTreeArray(tree, type) {
      return tree
        .filter((item) => item.type === type)
        .map((item) => {
          if (item.type !== type) {
            item = {};
          } else {
            item = Object.assign({}, item);
            if (item.children) {
              item.children = this.filterTreeArray(item.children, type);
            }
          }
          return item;
        });
    },
    async getTenantChildOrganizeAuthTreeData() {
      let list = [];
      return list;
    },
    onClose() {},
    clear() {
      if (this.selectDisabled) return;
      this.innerValue = "";
      this.selectedData = [];
      this.selectedIds = [];
      this.tagsList = [];
      this.$emit("input", []);
      this.$emit("change", [], []);
    },
    async openDialog() {
      if (this.selectDisabled) return;
      this.keyword = "";
      this.treeData = [];
      await this.getData();
      await this.setDefault();
      this.visible = true;
    },
    search() {
      this.$refs.tree && this.$refs.tree.filter(this.keyword);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data[this.props.label].indexOf(value) !== -1;
    },
    getNodePath(node) {
      let fullPath = [];
      const loop = (node) => {
        if (node.level) fullPath.unshift(node.data);
        if (node.parent) loop(node.parent);
      };
      loop(node);
      return fullPath;
    },
    handleNodeClick(data) {
      if (data.disabled || data.fullName === '顶级节点') return
      const isNextOrg = data.organize.indexOf(data.fullName) > -1
      let currId = isNextOrg ? data.organizeIds : [...data.organizeIds, data.id]
      let currData = isNextOrg ? data.organize : `${data.organize}/${data.fullName}`
      if (this.multiple) {
        const boo = this.selectedIds.some(o => o.join('/') === currId.join('/'))
        if (boo) return
        this.selectedIds.push(currId)
        this.selectedData.push(currData)
      } else {
        this.selectedIds = [currId]
        this.selectedData = [currData]
      }
    },
    removeAll() {
      this.selectedData = [];
      this.selectedIds = [];
    },
    removeData(index) {
      this.selectedData.splice(index, 1);
      this.selectedIds.splice(index, 1);
    },
    confirm() {
      let selectedData = [];
      for (let i = 0; i < this.selectedIds.length; i++) {
        let item = [];
        const selectedDataCopy = JSON.parse(JSON.stringify(this.selectedData));
        let selectedNames = selectedDataCopy[i].split("/");
        for (let j = 0; j < this.selectedIds[i].length; j++) {
          item.push({
            id: this.selectedIds[i][j],
            fullName: selectedNames[j],
          });
        }
        selectedData.push(item);
      }
      if (this.multiple) {
        this.innerValue = "";
        this.tagsList = JSON.parse(JSON.stringify(this.selectedData));
        this.$emit("input", this.selectedIds);
        this.$emit("change", this.selectedIds, selectedData);
      } else {
        this.innerValue = this.selectedData.join(",");
        this.$emit("input", this.selectedIds[0]);
        this.$emit("change", this.selectedIds[0], selectedData[0]);
      }
      this.resetInputHeight();
      this.visible = false;
    },
    setDefault() {
      if (!this.modelValue || !this.modelValue.length) {
        this.innerValue = "";
        this.selectedIds = [];
        this.selectedData = [];
        this.tagsList = [];
        return;
      }
      let selectedIds = this.multiple ? this.modelValue : [this.modelValue];
      this.selectedIds = JSON.parse(JSON.stringify(selectedIds));

      this.selectedData = this.selectedIds
        .map((record) => {
          const targetId = record[record.length - 1];
          const targetItem = this.allList.find((item) => item.id === targetId);
          if (!!targetItem) {
            return targetItem.organize;
          }
        })
        .filter((item) => item !== undefined);

      if (this.multiple) {
        this.innerValue = "";
        this.tagsList = JSON.parse(JSON.stringify(this.selectedData));
        this.$nextTick(() => {
          this.resetInputHeight();
        });
      } else {
        this.innerValue = this.selectedData.join(",");
      }
    },
    deleteTag(event, index) {
      this.selectedData.splice(index, 1);
      this.selectedIds.splice(index, 1);
      this.confirm();
      event.stopPropagation();
    },
    handleClearClick(event) {
      this.selectedData = [];
      this.selectedIds = [];
      this.confirm();
      event.stopPropagation();
    },
    resetInputWidth() {
      const reference = this.$refs.reference;
      if (reference && reference.$el) {
        this.inputWidth =
          this.$refs.reference.$el.getBoundingClientRect().width;
      }
    },
    handleResize() {
      this.resetInputWidth();
      if (this.multiple) this.resetInputHeight();
    },
    resetInputHeight() {
      if (this.collapseTags) return;
      this.$nextTick(() => {
        if (!this.$refs.reference) return;
        let input = this.$refs.reference.ref;
        const tags = this.$refs.tags;
        const tagsHeight = tags
          ? Math.round(tags.getBoundingClientRect().height)
          : 0;
        const sizeInMap = this.initialInputHeight || 40;
        console.log(input, 6677777777);
        input.style.height =
          this.selectedData.length === 0
            ? sizeInMap + "px"
            : Math.max(
                tags ? tagsHeight + (tagsHeight > sizeInMap ? 6 : 0) : 0,
                sizeInMap
              ) + "px";
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-select {
  position: relative;
}

::v-deep .el-select__tags {
  position: absolute;
  // max-width: inherit !important;
}

.popupSelect-container {
  width: 100%;

  .el-select__tags {
    max-height: 8rem;
    overflow: auto;

    .el-tag {
      max-width: 260px;
      word-break: break-all;
      height: fit-content;
      white-space: pre-wrap;
    }
  }
}

.NameClass {
  color: #1890ff;
  margin-right: 5px;
}

.icon-lx-tree-organization3:before {
  margin-right: 5px;
  color: #ec8b0f;
}

.el-tag {
  margin: 2px 0 2px 6px;
}

.el-select__tags-text {
  white-space: pre-wrap;
}

.el-select__tags {
  position: absolute;
  line-height: normal;
  white-space: normal;
  z-index: 1;
  top: 50%;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

.el-icon {
  cursor: pointer;
}
</style>